const urls = window.location.href;
const hasUrl = urls.includes('music.douyin.com/qishui/share/track?track_id');
 
// 监听来自popup的刷新请求
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "refreshAudio") {
    findAudioElements();
    sendResponse({status: "success"});
    return;
  }
  if (request.action === "onLoads")sendResponse({hasUrl})
  if (request.action === "ListGo"){
    location.href = request.url
    sendResponse({})
  }
  
  return true; // MV3 必须！
});

// 查找音频元素
function findAudioElements() {
  const audioElements = document.querySelectorAll('audio');
  const audioUrls = [];
  let ify = false;
  audioElements.forEach(audio => {
    if (audio.src) {
      ify = true;
      audioUrls.push({
        url:audio.src,
        name:document.querySelector('h1[class="title"]').textContent,
        adam:document.querySelector('span[class="artist-name-max"]').textContent,
        img:document.querySelector('div[id="root"] div div div div div div div div div div img').src,  
      });
    }
  });
  chrome.runtime.sendMessage({
    from: 'content',
    name: 'tubiao',
    data:ify ? '有':'无'
  });
  if(ify){
        // 存储并发送到popup
        chrome.storage.local.set({ 'douyinAudioUrls':audioUrls}, () => {
            chrome.runtime.sendMessage({
              from:"content",
              name:"onLoad",
              data:audioUrls
            });
        });
  } 
}

if(hasUrl){
  chrome.runtime.sendMessage({
    from: "content",
    name: "tubiao",
    data:'搜'
  }); 
  setTimeout(findAudioElements,3000)
}

console.log('__Code Art 汽水音乐解析器已开启__');
 
 